package me.jiatao.baselibrary.ext

import me.jiatao.baselibrary.utils.Preference
import java.util.regex.Pattern

/***
 * 手机号码检测
 */
fun checkPhoneNum(num: String): Boolean {
    val regExp = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(14[5-9])|(166)|(19[8,9])|)\\d{8}$"
    val p = Pattern.compile(regExp)
    val m = p.matcher(num)
    return m.matches()
}


/**
 * cookie编码成字符串
 */
fun encodeCookie(cookies: List<String>): String {
    val sb = StringBuilder()
    val set = HashSet<String>()
    cookies
        .map { cookie ->
            cookie.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        }
        .forEach {
            it.filterNot { set.contains(it) }.forEach { set.add(it) }
        }
    val ite = set.iterator()
    while (ite.hasNext()) {
        val cookie = ite.next()
        sb.append(cookie).append(";")
    }
    val last = sb.lastIndexOf(";")
    if (sb.length - 1 == last) {
        sb.deleteCharAt(last)
    }
    return sb.toString()
}

/**
 * 保存Cookie到SP
 */
fun saveCookie(url: String?, domain: String?, cookies: String) {
    url ?: return
    var spUrl: String by Preference(url, cookies)
    @Suppress("UNUSED_VALUE")
    spUrl = cookies
    domain ?: return
    var spDomain: String by Preference(
        domain,
        cookies
    )
    @Suppress("UNUSED_VALUE")
    spDomain = cookies
}